package org.example.jol;

import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.CountDownLatch;

public class HeavyweightLock {
    public static void main(String[] args) throws Exception{
        Thread.sleep(5000);
        Student student = new Student();
        System.out.println("获取锁之前，计算hashCode之前");
        System.out.println(ClassLayout.parseInstance(student).toPrintable());

        CountDownLatch latch = new CountDownLatch(3);

        Thread a = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (student) {
                    System.out.println("第一次获取锁之后，锁状态为，应该为偏向锁：");
                    System.out.println(ClassLayout.parseInstance(student).toPrintable());

                    latch.countDown();

                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        a.start();

        Thread.sleep(100);

        Thread b = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (student) {
                    // TODO ThreadId 应该为b线程的ID
                    System.out.println("第二次获取锁之后，锁状态为，应该为轻量级锁");
                    System.out.println(ClassLayout.parseInstance(student).toPrintable());

                    latch.countDown();

                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        b.start();

        Thread.sleep(1000);

        Thread c = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (student) {
                    // TODO ThreadId 应该为b线程的ID
                    System.out.println("第三次获取锁之后，锁状态为，应该为重量级锁");
                    System.out.println(ClassLayout.parseInstance(student).toPrintable());

                    latch.countDown();

                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        c.start();

        latch.await();

        System.out.println("释放锁之后，锁状态为");
        System.out.println(ClassLayout.parseInstance(student).toPrintable());

        Thread.sleep(Integer.MAX_VALUE);
    }
}
